package org.example.compare.schedule;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.example.compare.dto.*;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 测试数据生成器类，用于为calculateItem_10函数生成测试数据
 * 该函数使用到的非函数参数列表外部变量包括:
 * 1. hProcessSet - 需要进行排产的工序集
 * 2. sPositionsScore - 可以排产的工位
 * 3. hScoreByProcess - 按工序查找的分数表
 */
public class CalculateItem10TestDataGenerator {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Random random = new Random();

    static {
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 生成随机测试数据并保存到文件
     */
    public static void generateRandomTestData(int iteration) throws IOException {
        String basePath = "../../test_data/calculateItem_10/random_case_" + iteration;
        File baseDir = new File(basePath);

        // 清空文件夹
        clearDirectory(baseDir);

        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }

        // 先生成可以排产的工位数据
        Set<Long> sPositionsScore = generatePositionScoreData(basePath);
        
        // 生成工序集数据和分数表数据，确保有黑名单工位在分数表中
        Map<Long, OrderProcess> hProcessSet = generateProcessSetData(basePath, sPositionsScore);
        generateScoreByProcessData(basePath, hProcessSet, sPositionsScore);
    }

    /**
     * 生成手动测试数据并保存到文件
     */
    public static void generateManualTestData(int caseNumber) throws IOException {
        String basePath = "../../test_data/calculateItem_10/manual_case_" + caseNumber;
        File baseDir = new File(basePath);

        // 清空文件夹
        clearDirectory(baseDir);

        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }

        if (caseNumber == 1) {
            generateManualTestCase1(basePath);
        } else if (caseNumber == 2) {
            generateManualTestCase2(basePath);
        }
    }

    /**
     * 生成手动测试案例1 - 基本正常情况
     */
    private static void generateManualTestCase1(String basePath) throws IOException {
        // 生成工序集数据
        Map<Long, OrderProcess> hProcessSet = new HashMap<>();

        // 工序1 (正常状态，有黑名单工位)
        OrderDto dummyOrder = OrderDto.InitOrder();
        OrderProcess process1 = OrderProcess.InitOrderProcess(dummyOrder);
        process1.setProcessId(1001L);
        process1.setOrderProcessId(1001L);

        ProcessSch scheduling1 = new ProcessSch();
        scheduling1.setMbHoldFlag(false);
        scheduling1.setMbNGFlag(false);

        // 设置黑名单工位
        Set<Long> blackList1 = new HashSet<>();
        blackList1.add(10001L);
        scheduling1.setMisBlackList(blackList1);

        // 设置可做工位
        Set<Long> posCanDo1 = new HashSet<>();
        posCanDo1.add(10001L);
        posCanDo1.add(10002L);
        scheduling1.setMPosCanDo(posCanDo1);

        process1.setMScheduling(scheduling1);
        hProcessSet.put(1001L, process1);

        // 工序2 (挂起状态)
        OrderProcess process2 = OrderProcess.InitOrderProcess(dummyOrder);
        process2.setProcessId(1002L);
        process2.setOrderProcessId(1002L);

        ProcessSch scheduling2 = new ProcessSch();
        scheduling2.setMbHoldFlag(true); // 挂起状态
        scheduling2.setMbNGFlag(false);

        // 设置黑名单工位
        Set<Long> blackList2 = new HashSet<>();
        blackList2.add(10003L);
        scheduling2.setMisBlackList(blackList2);

        // 设置可做工位
        Set<Long> posCanDo2 = new HashSet<>();
        posCanDo2.add(10003L);
        posCanDo2.add(10004L);
        scheduling2.setMPosCanDo(posCanDo2);

        process2.setMScheduling(scheduling2);
        hProcessSet.put(1002L, process2);

        // 工序3 (NG状态)
        OrderProcess process3 = OrderProcess.InitOrderProcess(dummyOrder);
        process3.setProcessId(1003L);
        process3.setOrderProcessId(1003L);

        ProcessSch scheduling3 = new ProcessSch();
        scheduling3.setMbHoldFlag(false);
        scheduling3.setMbNGFlag(true); // NG状态

        // 设置黑名单工位
        Set<Long> blackList3 = new HashSet<>();
        blackList3.add(10005L);
        scheduling3.setMisBlackList(blackList3);

        // 设置可做工位
        Set<Long> posCanDo3 = new HashSet<>();
        posCanDo3.add(10005L);
        scheduling3.setMPosCanDo(posCanDo3);

        process3.setMScheduling(scheduling3);
        hProcessSet.put(1003L, process3);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hProcessSet.json"), hProcessSet);

        // 生成可以排产的工位数据
        Set<Long> sPositionsScore = new HashSet<>();
        sPositionsScore.add(10001L);
        sPositionsScore.add(10002L);
        sPositionsScore.add(10003L);
        sPositionsScore.add(10004L);
        sPositionsScore.add(10005L);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/sPositionsScore.json"), sPositionsScore);

        // 生成按工序查找的分数表数据
        Map<Long, List<Score>> hScoreByProcess = new HashMap<>();

        // 工序1的分数
        List<Score> scores1 = new ArrayList<>();
        Score score1_1 = new Score();
        score1_1.setPositionId(10001L);
        score1_1.setTotal(80.0);
        double[] scoreItems1 = new double[20];
        Arrays.fill(scoreItems1, 5.0);
        score1_1.setScoreItem(scoreItems1);
        scores1.add(score1_1);

        Score score1_2 = new Score();
        score1_2.setPositionId(10002L);
        score1_2.setTotal(75.0);
        double[] scoreItems2 = new double[20];
        Arrays.fill(scoreItems2, 4.5);
        score1_2.setScoreItem(scoreItems2);
        scores1.add(score1_2);

        hScoreByProcess.put(1001L, scores1);

        // 工序2的分数 (挂起状态)
        List<Score> scores2 = new ArrayList<>();
        Score score2_1 = new Score();
        score2_1.setPositionId(10003L);
        score2_1.setTotal(85.0);
        double[] scoreItems3 = new double[20];
        Arrays.fill(scoreItems3, 6.0);
        score2_1.setScoreItem(scoreItems3);
        scores2.add(score2_1);

        Score score2_2 = new Score();
        score2_2.setPositionId(10004L);
        score2_2.setTotal(70.0);
        double[] scoreItems4 = new double[20];
        Arrays.fill(scoreItems4, 4.0);
        score2_2.setScoreItem(scoreItems4);
        scores2.add(score2_2);

        hScoreByProcess.put(1002L, scores2);

        // 工序3的分数 (NG状态)
        List<Score> scores3 = new ArrayList<>();
        Score score3_1 = new Score();
        score3_1.setPositionId(10005L);
        score3_1.setTotal(90.0);
        double[] scoreItems5 = new double[20];
        Arrays.fill(scoreItems5, 6.5);
        score3_1.setScoreItem(scoreItems5);
        scores3.add(score3_1);

        hScoreByProcess.put(1003L, scores3);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hScoreByProcess.json"), hScoreByProcess);
    }

    /**
     * 生成手动测试案例2 - 包含复杂黑名单情况
     */
    private static void generateManualTestCase2(String basePath) throws IOException {
        // 生成工序集数据
        Map<Long, OrderProcess> hProcessSet = new HashMap<>();

        // 工序1 (正常状态，多个黑名单工位)
        OrderDto dummyOrder = OrderDto.InitOrder();
        OrderProcess process1 = OrderProcess.InitOrderProcess(dummyOrder);
        process1.setProcessId(2001L);
        process1.setOrderProcessId(2001L);

        ProcessSch scheduling1 = new ProcessSch();
        scheduling1.setMbHoldFlag(false);
        scheduling1.setMbNGFlag(false);

        // 设置多个黑名单工位
        Set<Long> blackList1 = new HashSet<>();
        blackList1.add(20001L);
        blackList1.add(20002L);
        scheduling1.setMisBlackList(blackList1);

        // 设置可做工位
        Set<Long> posCanDo1 = new HashSet<>();
        posCanDo1.add(20001L);
        posCanDo1.add(20002L);
        posCanDo1.add(20003L);
        scheduling1.setMPosCanDo(posCanDo1);

        process1.setMScheduling(scheduling1);
        hProcessSet.put(2001L, process1);

        // 工序2 (黑名单工位不在可做工位中)
        OrderProcess process2 = OrderProcess.InitOrderProcess(dummyOrder);
        process2.setProcessId(2002L);
        process2.setOrderProcessId(2002L);

        ProcessSch scheduling2 = new ProcessSch();
        scheduling2.setMbHoldFlag(false);
        scheduling2.setMbNGFlag(false);

        // 设置黑名单工位（不在可做工位中）
        Set<Long> blackList2 = new HashSet<>();
        blackList2.add(20004L); // 这个工位不在可做工位中
        scheduling2.setMisBlackList(blackList2);

        // 设置可做工位
        Set<Long> posCanDo2 = new HashSet<>();
        posCanDo2.add(20001L);
        posCanDo2.add(20002L);
        scheduling2.setMPosCanDo(posCanDo2);

        process2.setMScheduling(scheduling2);
        hProcessSet.put(2002L, process2);

        // 工序3 (无黑名单工位)
        OrderProcess process3 = OrderProcess.InitOrderProcess(dummyOrder);
        process3.setProcessId(2003L);
        process3.setOrderProcessId(2003L);

        ProcessSch scheduling3 = new ProcessSch();
        scheduling3.setMbHoldFlag(false);
        scheduling3.setMbNGFlag(false);

        // 不设置黑名单工位（空集合）
        scheduling3.setMisBlackList(new HashSet<>());

        // 设置可做工位
        Set<Long> posCanDo3 = new HashSet<>();
        posCanDo3.add(20003L);
        scheduling3.setMPosCanDo(posCanDo3);

        process3.setMScheduling(scheduling3);
        hProcessSet.put(2003L, process3);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hProcessSet.json"), hProcessSet);

        // 生成可以排产的工位数据
        Set<Long> sPositionsScore = new HashSet<>();
        sPositionsScore.add(20001L);
        sPositionsScore.add(20002L);
        sPositionsScore.add(20003L);
        sPositionsScore.add(20004L);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/sPositionsScore.json"), sPositionsScore);

        // 生成按工序查找的分数表数据
        Map<Long, List<Score>> hScoreByProcess = new HashMap<>();

        // 工序1的分数（有黑名单工位）
        List<Score> scores1 = new ArrayList<>();
        Score score1_1 = new Score();
        score1_1.setPositionId(20001L);
        score1_1.setTotal(80.0);
        double[] scoreItems1 = new double[20];
        Arrays.fill(scoreItems1, 7.0);
        score1_1.setScoreItem(scoreItems1);
        scores1.add(score1_1);

        Score score1_2 = new Score();
        score1_2.setPositionId(20002L);
        score1_2.setTotal(75.0);
        double[] scoreItems2 = new double[20];
        Arrays.fill(scoreItems2, 6.5);
        score1_2.setScoreItem(scoreItems2);
        scores1.add(score1_2);

        Score score1_3 = new Score();
        score1_3.setPositionId(20003L);
        score1_3.setTotal(70.0);
        double[] scoreItems3 = new double[20];
        Arrays.fill(scoreItems3, 6.0);
        score1_3.setScoreItem(scoreItems3);
        scores1.add(score1_3);

        hScoreByProcess.put(2001L, scores1);

        // 工序2的分数（黑名单工位不在可做工位中）
        List<Score> scores2 = new ArrayList<>();
        Score score2_1 = new Score();
        score2_1.setPositionId(20001L);
        score2_1.setTotal(85.0);
        double[] scoreItems4 = new double[20];
        Arrays.fill(scoreItems4, 7.5);
        score2_1.setScoreItem(scoreItems4);
        scores2.add(score2_1);

        Score score2_2 = new Score();
        score2_2.setPositionId(20002L);
        score2_2.setTotal(80.0);
        double[] scoreItems5 = new double[20];
        Arrays.fill(scoreItems5, 7.0);
        score2_2.setScoreItem(scoreItems5);
        scores2.add(score2_2);

        hScoreByProcess.put(2002L, scores2);

        // 工序3的分数（无黑名单工位）
        List<Score> scores3 = new ArrayList<>();
        Score score3_1 = new Score();
        score3_1.setPositionId(20003L);
        score3_1.setTotal(90.0);
        double[] scoreItems6 = new double[20];
        Arrays.fill(scoreItems6, 8.0);
        score3_1.setScoreItem(scoreItems6);
        scores3.add(score3_1);

        hScoreByProcess.put(2003L, scores3);

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hScoreByProcess.json"), hScoreByProcess);
    }

    /**
     * 清空指定目录下的所有文件
     *
     * @param directory 要清空的目录
     * @throws IOException IO异常
     */
    private static void clearDirectory(File directory) throws IOException {
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        Files.delete(file.toPath());
                    }
                }
            }
        }
    }

    /**
     * 生成工序集数据
     */
    private static Map<Long, OrderProcess> generateProcessSetData(String basePath, Set<Long> sPositionsScore) throws IOException {
        Map<Long, OrderProcess> hProcessSet = new HashMap<>();

        // 随机生成工序数量 3-8个
        int processCount = 3 + random.nextInt(6);

        OrderDto dummyOrder = OrderDto.InitOrder();

        // 转换为列表以便随机选择
        List<Long> positionIdList = new ArrayList<>(sPositionsScore);

        for (int i = 0; i < processCount; i++) {
            OrderProcess process = OrderProcess.InitOrderProcess(dummyOrder);
            long processId = 1000L + i * 10 + random.nextInt(10);
            process.setProcessId(processId);
            process.setOrderProcessId(processId);

            ProcessSch scheduling = new ProcessSch();
            scheduling.setMbHoldFlag(random.nextDouble() < 0.1); // 10%概率为挂起状态
            scheduling.setMbNGFlag(random.nextDouble() < 0.1); // 10%概率为NG状态

            // 设置黑名单工位，确保至少有一些工位在sPositionsScore中
            Set<Long> blackList = new HashSet<>();
            if (random.nextDouble() < 0.7) { // 70%概率设置黑名单工位
                int blackListCount = 1 + random.nextInt(Math.min(3, Math.max(1, positionIdList.size()))); // 1-3个黑名单工位
                // 随机选择一些在sPositionsScore中的工位作为黑名单工位
                Collections.shuffle(positionIdList);
                for (int j = 0; j < blackListCount && j < positionIdList.size(); j++) {
                    blackList.add(positionIdList.get(j));
                }
            }
            scheduling.setMisBlackList(blackList);

            // 设置可做工位集合
            Set<Long> posCanDo = new HashSet<>(sPositionsScore);
            scheduling.setMPosCanDo(posCanDo);

            process.setMScheduling(scheduling);
            hProcessSet.put(processId, process);
        }

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hProcessSet.json"), hProcessSet);

        return hProcessSet;
    }
    
    private static Map<Long, OrderProcess> generateProcessSetData(String basePath) throws IOException {
        Map<Long, OrderProcess> hProcessSet = new HashMap<>();

        // 随机生成工序数量 3-8个
        int processCount = 3 + random.nextInt(6);

        OrderDto dummyOrder = OrderDto.InitOrder();

        for (int i = 0; i < processCount; i++) {
            OrderProcess process = OrderProcess.InitOrderProcess(dummyOrder);
            long processId = 1000L + i * 10 + random.nextInt(10);
            process.setProcessId(processId);
            process.setOrderProcessId(processId);

            ProcessSch scheduling = new ProcessSch();
            scheduling.setMbHoldFlag(random.nextDouble() < 0.1); // 10%概率为挂起状态
            scheduling.setMbNGFlag(random.nextDouble() < 0.1); // 10%概率为NG状态

            // 设置黑名单工位
            Set<Long> blackList = new HashSet<>();
            if (random.nextDouble() < 0.7) { // 70%概率设置黑名单工位
                int blackListCount = 1 + random.nextInt(3); // 1-3个黑名单工位
                for (int j = 0; j < blackListCount; j++) {
                    blackList.add((long) (10000 + random.nextInt(90000))); // 10000-99999的工位ID
                }
            }
            scheduling.setMisBlackList(blackList);

            // 设置可做工位集合
            Set<Long> posCanDo = new HashSet<>();
            int posCount = 2 + random.nextInt(5); // 2-6个工位
            for (int j = 0; j < posCount; j++) {
                posCanDo.add((long) (10000 + random.nextInt(90000))); // 10000-99999的工位ID
            }
            scheduling.setMPosCanDo(posCanDo);

            process.setMScheduling(scheduling);
            hProcessSet.put(processId, process);
        }

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hProcessSet.json"), hProcessSet);

        return hProcessSet;
    }

    /**
     * 生成可以排产的工位数据
     */
    private static Set<Long> generatePositionScoreData(String basePath) throws IOException {
        Set<Long> sPositionsScore = new HashSet<>();

        // 随机生成工位数量 5-15个
        int positionCount = 5 + random.nextInt(11);

        // 添加测试工位ID
        for (int i = 0; i < positionCount; i++) {
            sPositionsScore.add((long) (10000 + random.nextInt(90000))); // 10000-99999的工位ID
        }

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/sPositionsScore.json"), sPositionsScore);

        return sPositionsScore;
    }

    /**
     * 生成按工序查找的分数表数据
     */
    private static void generateScoreByProcessData(String basePath, Map<Long, OrderProcess> hProcessSet,
                                                   Set<Long> sPositionsScore) throws IOException {
        Map<Long, List<Score>> hScoreByProcess = new HashMap<>();

        // 使用已生成的工序ID来创建分数数据
        List<Long> processIds = new ArrayList<>(hProcessSet.keySet());
        
        // 收集所有工序的黑名单工位
        Set<Long> allBlackListPositions = new HashSet<>();
        for (OrderProcess process : hProcessSet.values()) {
            allBlackListPositions.addAll(process.getMScheduling().getMisBlackList());
        }

        for (Long processId : processIds) {
            List<Score> scores = new ArrayList<>();

            // 获取工位ID列表
            List<Long> positionIds = new ArrayList<>(sPositionsScore);
            
            // 确保至少有一个黑名单工位在分数表中
            List<Long> blackListPosList = new ArrayList<>(hProcessSet.get(processId).getMScheduling().getMisBlackList());
            if (!blackListPosList.isEmpty()) {
                // 添加至少一个黑名单工位到分数表中
                Long blackPos = blackListPosList.get(random.nextInt(blackListPosList.size()));
                if (!positionIds.contains(blackPos)) {
                    positionIds.add(blackPos);
                }
            }
            
            Collections.shuffle(positionIds); // 随机打乱

            // 每个工序对应1-5个工位分数（不超过工位总数）
            int scoreCount = Math.min(1 + random.nextInt(5), positionIds.size());
            for (int j = 0; j < scoreCount; j++) {
                Score score = new Score();
                score.setPositionId(positionIds.get(j));
                // 总分保留两位小数
                double total = random.nextDouble() * 100; // 0-100的总分
                total = new BigDecimal(total).setScale(2, RoundingMode.HALF_UP).doubleValue();
                score.setTotal(total);

                // 初始化分数项数组，包含随机分数，每项保留两位小数
                double[] scoreItems = new double[20];
                for (int k = 0; k < scoreItems.length; k++) {
                    double item = random.nextDouble() * 50; // 0-50的分数项
                    item = new BigDecimal(item).setScale(2, RoundingMode.HALF_UP).doubleValue();
                    scoreItems[k] = item;
                }
                score.setScoreItem(scoreItems);

                scores.add(score);
            }

            hScoreByProcess.put(processId, scores);
        }

        // 保存到文件
        objectMapper.writeValue(new File(basePath + "/hScoreByProcess.json"), hScoreByProcess);
    }

    public static void main(String[] args) {
        try {
            // 确保主目录存在
            File mainDir = new File("../../test_data/calculateItem_10");
            if (!mainDir.exists()) {
                mainDir.mkdirs();
            }

            // 生成50组随机测试数据
            for (int i = 1; i <= 50; i++) {
                generateRandomTestData(i);
                System.out.println("随机测试数据集 " + i + " 已成功生成");
            }

            // 生成2个手动测试案例
            for (int i = 1; i <= 2; i++) {
                generateManualTestData(i);
                System.out.println("手动测试案例 " + i + " 已成功生成");
            }

            System.out.println("所有测试数据已成功生成并保存到../../test_data/calculateItem_10目录下");
        } catch (IOException e) {
            System.err.println("生成测试数据时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}